package training.bms.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import training.bms.business.Blog;

public class BlogDAO  implements IBlogDAO{

	private EntityManagerFactory factory;

	public BlogDAO(){

		factory = Persistence.createEntityManagerFactory("BMS");

	}

	public void insertBlog(Blog blog) {
		EntityManager manager = null;
		EntityTransaction transaction = null;

		try {
			manager = factory.createEntityManager();
			transaction = manager.getTransaction();
			transaction.begin();
			manager.persist(blog);
			manager.flush();
			transaction.commit();

		}catch(RuntimeException e) {
			if (transaction != null){
				try{
				transaction.getRollbackOnly();
				}catch (RuntimeException ex) {
					ex.printStackTrace();
				}
			}
		}finally{
			try{
				if (manager != null){
					manager.close();
				}				
			}catch(RuntimeException e){
				e.printStackTrace();
			}
		}

		
	}

	public Blog selectBlog(String name) {
		EntityManager manager = null;
		StringBuilder jpql = new StringBuilder("select b from ");
		jpql.append(Blog.class.getName());
		jpql.append(" b where trim(lower(b.name)) = :blogName");
		try {
			manager = factory.createEntityManager();
			TypedQuery<Blog> query = manager.createQuery(jpql.toString(), Blog.class);
			query.setParameter("blogName", name.toLowerCase().trim());
			List<Blog> result = query.getResultList();
			if (result.isEmpty()){
				return null;
			}else{
				return result.get(0);
			}
		}finally{
			try{
				if (manager != null){
					manager.close();
				}				
			}catch(RuntimeException e){
				e.printStackTrace();
			}
		}

		
		
	}

}
